<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>取消请求</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body>
    <button>发送</button>
    <button>取消</button>

    <script>
        let btns = document.querySelectorAll("button");
        //1. 声明外部变量
        let cancel = null;

        btns[0].onclick =async function(){
            //判断是否正在发送请求
            if(cancel !== null){ 
                //如果之前有请求正在发送, 直接取消请求
                cancel();
            }
            let result = await axios.get('http://127.0.0.1/delay-server', {
                //2. 在配置对象中, 设置 cancelToken 属性
                cancelToken: new axios.CancelToken(c => {
                    cancel = c;
                })
            });
            //发送请求完成以后, 将 cancel 复原 (完善)
            cancel = null;
        }

        btns[1].onclick = function(){
            //3. 调用 cancel 函数即可 
            cancel();
        }
    </script>
</body>

</html>